<script setup lang="ts">
import { ref, watch, reactive, onMounted, computed, onUnmounted } from 'vue';
import { useBooleanStore } from '@/store';
import { debounce } from 'lodash-es';
import { Notification, TableRowSelection } from '@arco-design/web-vue';
import {
  AOSortingTaskPage,
  startSortingTask,
  materialDistribution,
  getToolCode,
  replaceToolCode,
  replaceToolCodeByHand,
  bindingWorkBin,
  cleanWaitingTask,
  getPackCode,
} from '@/api/sorting-matching';
import ColumnsList from './columns';

const columns: any[] = [
  {
    title: '托盘',
    dataIndex: 'toolCode',
    width: 160,
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '缓存箱',
    dataIndex: 'workbinCode',
    width: 160,
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: 'AO号',
    dataIndex: 'aoCode',
    width: 180,
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '站位',
    dataIndex: 'station',
    width: 120,
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '架次',
    dataIndex: 'planeNo',
    width: 120,
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },

  {
    title: '工作包号',
    dataIndex: 'packageCode',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '图号',
    dataIndex: 'itemCode',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
    width: 180,
    ellipsis: true,
    tooltip: true,
  },

  {
    title: '型号',
    dataIndex: 'mproductNumber',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '质量编号',
    dataIndex: 'qualityCode',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
    width: 180,
    ellipsis: true,
    tooltip: true,
  },

  {
    title: '分拣状态',
    dataIndex: 'isSortName',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
];
// 列表头部
const { ruleColumns } = ColumnsList();
const rowSelection: TableRowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});
const selectedKeys = ref<any>([]);
// 创建一个响应式的本地副本
const localTableData = ref<any[]>([]);

// 搜索条件
const aoCode = ref<string>('');
const planeNo = ref<string>('');
const station = ref<string>('');
const toolCode = ref<string>('');
// 数据库一共有多少条
const total = ref<number>(0);
const pageNum = ref<number>(1);
const pageSize = ref<number>(30);

// 表格数据
async function handleSearch() {
  const data = await AOSortingTaskPage({
    aoCode: aoCode.value,
    planeNo: planeNo.value,
    station: station.value,
    toolCode: toolCode.value,
    size: pageSize.value,
    current: pageNum.value,
  });

  localTableData.value = data.responseBody?.records || [];
  total.value = data.responseBody?.total || 0;
}

const booleanStore = useBooleanStore();

const btnIsFalse = ref<boolean>(false);
const intervalFalse = ref<boolean>(false);
const intervalId = ref<any>(null); // 用来保存定时器 ID

// 当前托盘
const currentTool = ref<any[]>([]);
// 当前箱
const currentWorkBin = ref<any[]>([]);
// 托盘队列
const toolQueue = ref<any[]>([]);
// 箱队列
const workBinQueue = ref<any[]>([]);
// 等待托盘
const waitTool = ref<any[]>([]);
// 等待箱
const waitWorkBin = ref<any[]>([]);
// 勾选的数据
const selectedTableData = computed(() => {
  return localTableData.value.filter((item: any) =>
    selectedKeys.value.includes(item.mesCheckQualiticationId)
  );
});

// 执行任务
async function startSorting() {
  if (selectedKeys.value.length === 0) {
    Notification.warning({
      title: '提示',
      content: '请选择任务',
      closable: true,
    });
    return;
  }
  // 将筛选后的数组变为响应式数组
  const selectedSort = reactive(
    localTableData.value.filter((item) =>
      selectedKeys.value.includes(item.mesCheckQualiticationId)
    )
  );

  const data = await startSortingTask(selectedSort);
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: '作业开始成功',
      closable: true,
    });
    btnIsFalse.value = !btnIsFalse.value;
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
  selectedKeys.value = [];
}

// 调整队列
const handleChange = (_data: any) => {
  localTableData.value = _data;
};

// 托盘列表
const toolDataList = ref<any[]>([]);
const visible = ref<boolean>(false);
const selected = ref<any[]>([]);
// 查询更换托盘箱子
async function showReplaceToolView() {
  // console.log(selectedTableData.value);

  if (selectedKeys.value.length !== 1) {
    Notification.warning({
      title: '提示',
      content: '请勾选一条需要更改托盘的数据',
      closable: true,
    });
    return;
  }
  const data = await getToolCode(selectedTableData.value[0]);
  toolDataList.value = data.responseBody || [];
  visible.value = true;
}
// 保存托盘更改
async function replaceToolOk() {
  if (selected.value.length !== 1) {
    Notification.warning({
      title: '提示',
      content: '请勾选一条托盘数据',
      closable: true,
    });
    return;
  }
  const data = await replaceToolCode({
    sourceToolCode: selectedTableData.value[0]?.toolCode,
    targetToolCode: selected.value[0],
  });
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
  selected.value = [];
  visible.value = false;
  booleanStore.toggleBool4(4);
  handleSearch();
}
const inputTool = ref<string>('');

const visible3 = ref<boolean>(false);

// 手动更改托盘
async function replaceTool() {
  inputTool.value = '';
  visible3.value = true;
}
// 保存手动更改托盘
async function okSaveTool() {
  if (!inputTool.value.startsWith('21208003')) {
    Notification.warning({
      title: '提示',
      content: '输入的托盘信息不正确',
      closable: true,
    });
    return;
  }
  const data = await replaceToolCodeByHand({
    toolCode: inputTool.value,
    msTaskAoId: selectedTableData.value[0].msTaskAoId,
    msAssginWorkbintoolRelId:
      selectedTableData.value[0].msAssginWorkbintoolRelId,
  });
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
    visible3.value = false;
    selected.value = [];
    visible.value = false;
    booleanStore.toggleBool4(4);
    handleSearch();
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}
// 绑定托盘箱子
async function bindWorkbinTool() {
  const data = await bindingWorkBin({});
  if (data.message) {
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}

// 点击收缩列表
const isShrink = ref<boolean>(true);
function shrinkY() {
  isShrink.value = true;
}
function shrinkN() {
  isShrink.value = false;
}

// 清理等待任务
async function cleanWaiting() {
  const data = await cleanWaitingTask({});
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}

// 缓存箱任务下发
async function taskGoOn() {
  const data = await materialDistribution({});
  if (data.retCode === '200') {
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}
// 增加防抖避免点击多次
const debouncedTaskGoOn = debounce(taskGoOn, 5000, {
  leading: true, // 立即执行
  trailing: false, // 不在延迟结束后执行
});

// 查看工作包规则
const ruleList = ref<any[]>([]);
const visible4 = ref<boolean>(false);
async function lookupPackageRule() {
  if (selectedTableData.value.length < 1) {
    Notification.warning({
      title: '提示',
      content: '请至少选择一条数据',
      closable: true,
    });
    return;
  }
  const data = await getPackCode({
    packageCode: selectedTableData.value[0].packageCode,
  });
  if (data.retCode === '200') {
    ruleList.value = data.responseBody;
    visible4.value = true;
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}

function change(e: any) {
  pageNum.value = e;
}
function changeSize(e: any) {
  pageSize.value = e;
}

watch([pageNum, pageSize], () => {
  handleSearch();
});

// 停止定时器
function stopInterval() {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    intervalId.value = null; // 清除定时器 ID
  }
}

onMounted(() => {
  handleSearch();
});
onUnmounted(() => {
  debouncedTaskGoOn.cancel(); // 清理debounce以防内存泄漏
});
watch(
  () => booleanStore.boolValue3,
  () => {
    if (booleanStore.num3 === 7) {
      handleSearch();
    }
  }
);
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6" style="margin-bottom: 10px">
      <a-input
        v-model="toolCode"
        placeholder="托盘"
        size="large"
        allow-clear
        @keyup.enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" style="margin-bottom: 10px">
      <a-input
        v-model="planeNo"
        placeholder="架次"
        size="large"
        allow-clear
        @keyup.enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" style="margin-bottom: 10px">
      <a-input
        v-model="station"
        placeholder="站位"
        size="large"
        allow-clear
        @keyup.enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" style="margin-bottom: 10px">
      <a-input
        v-model="aoCode"
        placeholder="AO"
        size="large"
        allow-clear
        @keyup.enter="handleSearch"
      />
    </a-col>
    <a-col :span="24" style="margin-bottom: 10px">
      <a-button type="primary" size="large" @click="debouncedTaskGoOn"
        >缓存箱任务下发
      </a-button>
      <a-button
        type="primary"
        style="margin-left: 10px"
        size="large"
        @click="startSorting"
        >执行任务
      </a-button>
      <a-button
        type="primary"
        style="margin-left: 10px"
        size="large"
        @click="cleanWaiting"
        >清理等待任务
      </a-button>
      <a-button
        type="primary"
        style="margin-left: 10px"
        size="large"
        @click="handleSearch"
        >查询
      </a-button>
      <!-- <a-popconfirm
        content="你确定要进行这项操作码?"
        ok-text="确定"
        cancel-text="取消"
        @ok="bindWorkbinTool"
      >
        <a-button type="primary" style="margin-left: 10px" size="large"
          >绑定托盘箱子
        </a-button>
      </a-popconfirm>
      <a-button
        type="primary"
        style="margin-left: 10px"
        size="large"
        @click="showReplaceToolView"
        >更换托盘
      </a-button>
      <a-button
        type="primary"
        style="margin-left: 10px"
        size="large"
        @click="lookupPackageRule"
        >查看工作包规则
      </a-button> -->
    </a-col>
  </a-row>
  <a-table
    v-model:selectedKeys="selectedKeys"
    :stripe="true"
    row-key="mesCheckQualiticationId"
    :row-selection="rowSelection"
    class="top-table"
    :pagination="false"
    :columns="columns"
    :data="localTableData"
    column-resizable
    style="height: 250px"
    :scroll="{ y: 250 }"
    @change="handleChange"
  >
  </a-table>
  <div class="page-position">
    <a-pagination
      :total="total"
      :current="pageNum"
      :page-size="pageSize"
      show-total
      show-jumper
      :show-page-size="true"
      :page-size-options="[30, 50, 100, 500]"
      @change="change"
      @update:page-size="changeSize"
    />
  </div>

  <a-divider :size="2" />
  <!-- 更换托盘 -->
  <a-drawer
    v-model:visible="visible"
    width="800px"
    :footer="false"
    @cancel="() => (visible = false)"
  >
    <template #title> 更换托盘列表 </template>
    <a-space direction="vertical" fill>
      <div style="display: flex; margin-bottom: 5px">
        <a-button type="primary" size="large" @click="replaceToolOk"
          >更改托盘</a-button
        >
        <a-button
          type="primary"
          style="margin-left: 15px"
          size="large"
          @click="replaceTool"
          >手动更改托盘</a-button
        >
      </div>
      <a-table
        v-model:selectedKeys="selected"
        :stripe="true"
        class="top-table"
        :pagination="false"
        row-key="toolCode"
        :columns="columns"
        :data="toolDataList"
        :row-selection="rowSelection"
      >
      </a-table>
    </a-space>
  </a-drawer>
  <!-- 手动更改托盘 -->
  <a-modal
    v-model:visible="visible3"
    @cancel="() => (visible3 = !visible3)"
    @ok="okSaveTool"
  >
    <template #title> 手动更改托盘 </template>
    <span>请输入托盘:</span>
    <a-textarea v-model="inputTool" size="large" />
  </a-modal>
  <!-- 查看工作包规则 -->
  <a-drawer
    :width="840"
    :visible="visible4"
    :footer="false"
    unmount-on-close
    @cancel="(visible4 = !visible4), booleanStore.toggleBool4(4)"
  >
    <template #title> 查看工作包规则 </template>
    <div>
      <a-table
        :stripe="true"
        class="top-table"
        :pagination="false"
        :columns="ruleColumns"
        :data="ruleList"
        :scroll="{ y: 400 }"
        style="height: 250px"
      >
      </a-table>
    </div>
  </a-drawer>
</template>

<style scoped>
.current-font {
  color: #4ad953;
  font-weight: bold;
  font-size: 18px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.wait-font {
  color: #a7535a;
  font-weight: bold;
  font-size: 18px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.queue-font {
  color: #4c1f24;
  font-weight: bold;
  font-size: 18px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.queue-num {
  font-weight: 600;
  font-size: 18px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.col-contain {
  display: flex;
  justify-content: space-around;
}
.title-font {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
}
.task-font {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
.margin-top {
  margin-top: 10px;
}
.top-table {
  white-space: nowrap;
}
.page-position {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.div-container {
  display: flex;
  justify-content: start;
  align-items: center;
}
.icon {
  cursor: pointer; /* 鼠标悬停时显示为手指 */
  transition: transform 0.2s; /* 添加过渡效果 */
}
.icon:hover {
  transform: scale(1.1);
}

.clickable {
  cursor: pointer; /* 鼠标悬停时变成手指 */
  transition: color 0.3s; /* 平滑过渡效果 */
}

.clickable:hover {
  color: green; /* 鼠标悬停时改变字体颜色 */
  transform: scale(1.1);
}
.div-container {
  display: flex;
  justify-content: start;
  align-items: center;
}
</style>
